package hu.szyrt.bug.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class ResizableImageView extends ImageView implements OnTouchListener {

	
	private long downTime = 0;
	private Bitmap mBitmap;

	public ResizableImageView(Context context) {
		super(context);
		init();
	}
	public ResizableImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}
	public ResizableImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}
	
	private void init(){
		this.setOnTouchListener(this);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		if (mBitmap != null) {
			int viewWidth = MeasureSpec.getSize(widthMeasureSpec);
			int viewHeight = MeasureSpec.getSize(heightMeasureSpec);
			int height = viewWidth * mBitmap.getHeight() / mBitmap.getWidth();
			// ha nem fér el, akkor a levágott verzió
			if(height < viewHeight) height = viewHeight; 				
			setMeasuredDimension(viewWidth, height);			
		} else {
			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		}
	}

	@Override
	public void setImageBitmap(Bitmap bitmap) {
		mBitmap = bitmap;
		super.setImageBitmap(bitmap);
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {		
		if(event.getAction() == MotionEvent.ACTION_DOWN){
			downTime = event.getEventTime();
			return true;
		}else if(event.getAction() == MotionEvent.ACTION_UP){			
			long diff = event.getEventTime() - downTime;
			if(diff > 5 && diff < 350){				
				if(onGridClickListener != null){
					int rowIndex = event.getY() < (v.getHeight() >> 1) ? 0 : 1; 
					int columnIndex = event.getX() < (v.getWidth() >> 1) ? 0 : 1;
					onGridClickListener.onClick(rowIndex, columnIndex);
				}					
			}
			return true;
		}
		return false;
	}
	
	// Interfaces -----------------------------------------------
	OnGridClickListener onGridClickListener;
	public static interface OnGridClickListener{
		void onClick(int rowIndex, int columnIndex);
	}
	
	public void setOnGridClickListener(OnGridClickListener onGridClickListener) {
		this.onGridClickListener = onGridClickListener;
	}
	
	
}